package org.korifey.ffalg;

import java.util.Comparator;

public class Pair<A, B> {
	private A a;
	private B b;
	public Pair(A a, B b) {
		super();
		this.a = a;
		this.b = b;
	}
	public A A() {
		return a;
	}
	public B B() {
		return b;
	}
	
	public static <A,B> Pair<A,B> of(A a, B b) {
		return new Pair<A,B>(a, b);
	}
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((a == null) ? 0 : a.hashCode());
		result = prime * result + ((b == null) ? 0 : b.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Pair other = (Pair) obj;
		if (a == null) {
			if (other.a != null)
				return false;
		} else if (!a.equals(other.a))
			return false;
		if (b == null) {
			if (other.b != null)
				return false;
		} else if (!b.equals(other.b))
			return false;
		return true;
	}
	
	
	
	@Override
	public String toString() {
		return "[" + a + ", " + b + "]";
	}



	public static final PairComparator DEFAULT_COMPARATOR = new PairComparator(new Sorts.DefaultComparator(), new Sorts.DefaultComparator(), true); 
	
	public static class PairComparator<A,B> implements Comparator<Pair<A,B>> {
		private Comparator<A> compA;
		private Comparator<B> compB;
		private boolean aFirst;
		
		public PairComparator(Comparator<A> compA, Comparator<B> compB, boolean aFirst) {
			this.compA = compA != null ? compA : new Sorts.ZeroComparator<A>();
			this.compB = compB != null ? compB : new Sorts.ZeroComparator<B>();
			this.aFirst = aFirst;
		}
		
		
		public int compare(Pair<A, B> o1, Pair<A, B> o2) {
			if (aFirst) {
				int res = compA.compare(o1.a, o2.a);
				if (res != 0) return res;
				else return compB.compare(o1.b, o2.b);
			}
			else {
				int res = compB.compare(o1.b, o2.b);
				if (res != 0) return res;
				else return compA.compare(o1.a, o2.a);
			}
		}
		
	}
	
}
